元组(Tuple)
元组是固定长度和固定类型的数组,每个位置的类型是确定的。
// 基本元组
const user: [string, number] = ['Alice', 25]
// 标签元组(更可读)
const labeled: [name: string, age: number] = ['Alice', 25]
// 可选元素
const optional: [string, number?] = ['hello']
typescript
常见使用场景
// React的useState返回值就是元组
const [count, setCount] = useState<number>(0)
// Object.entries的类型
Object.entries({ name: 'Alice', age: 25 })
// 返回 [string, string | number][]
// 函数返回多个不同类型的值
function usePosition(): [x: number, y: number] {
return [100, 200]
}
typescript
枚举(Enum)
数字枚举
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
}
const dir: Direction = Direction.Up
typescript
字符串枚举
enum UserRole {
Admin = 'ADMIN',
Editor = 'EDITOR',
Viewer = 'VIEWER'
}
typescript
常量枚举(const enum)
const enum Status {
Active = 'ACTIVE',
Inactive = 'INACTIVE'
}
// 编译后直接内联值,不生成枚举对象
const s = Status.Active // 编译为 const s = "ACTIVE"
typescript
枚举的替代方案
很多项目更倾向于使用联合字面量类型替代枚举:
// 替代方案
type Status = 'active' | 'inactive' | 'pending'
type Role = 'admin' | 'editor' | 'viewer'
const status: Status = 'active'
typescript
这种方式的优点是类型更简单,无需引入额外的enum声明,且与JSON数据天然兼容。
↑